/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.trick.admin.cell;

import it.trick.admin.App;
import it.trick.admin.controller.AddPreViewController;
import it.trick.admin.controller.ChannelTopController;
import it.trick.admin.controller.DeleteContentsViewController;
import it.trick.admin.model.ContentsBaseModel;
import it.trick.admin.model.PreModel;
import java.util.ArrayList;
import java.util.List;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.ListCell;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.Pane;

/**
 *
 * @author takahara
 */
public class PreListViewCell extends ListCell<PreModel>{

    private ListCell listCell;
    private ContextMenu contextMenu = new ContextMenu();

    public PreListViewCell() {

        setListCell();

        // コンテキストメニューの初期化
        MenuItem publicMenuItem = new MenuItem("公開/非公開");
        MenuItem changeIndexUpperMenuItem = new MenuItem("上へ ↑");
        MenuItem changeIndexLowerMenuItem = new MenuItem("下へ ↓");
        MenuItem deletePageMenuItem = new MenuItem("削除");

        contextMenu.getItems().addAll(
                publicMenuItem,
                new SeparatorMenuItem(),
                changeIndexUpperMenuItem,
                changeIndexLowerMenuItem,
                new SeparatorMenuItem(),
                deletePageMenuItem);

        // ---------------------------------------------------------------------
        // 削除イベント
        // ---------------------------------------------------------------------
        deletePageMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                App.getInstance().showPopStage(getDeleteStageController(), "コンテンツ削除", 500, 150, true);
            }
        });

        // ---------------------------------------------------------------------
        // 公開・非公開
        // ---------------------------------------------------------------------
        publicMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                // POST処理
                ChannelTopController.getInstance().publicPreTask.setup(getItem().getKeyValueString());
                ChannelTopController.getInstance().publicPreTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                    @Override
                    public void handle(WorkerStateEvent t) {

                        ImageView icon;
                        if (!getItem().isDownloadFlg()) {
                            icon = new ImageView(new Image("it/trick/admin/resource/images/public_page.png"));
                        } else {
                            icon = new ImageView(new Image("it/trick/admin/resource/images/no_public.png"));
                        }

                        icon.setFitHeight(18.0);
                        icon.setPreserveRatio(true);
                        setGraphic(icon);

                        getItem().setDownloadFlg(!getItem().isDownloadFlg());
                    }
                });
                ChannelTopController.getInstance().publicPreTask.restart();
            }
        });

        // ---------------------------------------------------------------------
        // 上移動イベント
        // ---------------------------------------------------------------------
        changeIndexUpperMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {

                PreModel preModel = getItem();

                int nIndex = getListView().getItems().indexOf(getItem());
                if(nIndex > 0) {
                    getListView().getItems().remove(preModel);
                    getListView().getItems().add(nIndex - 1, preModel);

                    getListView().getSelectionModel().select(preModel);

                    changeIndex();
                }
            }
        });

        // ---------------------------------------------------------------------
        // 下移動イベント
        // ---------------------------------------------------------------------
        changeIndexLowerMenuItem.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                PreModel preModel = getItem();

                int nIndex = getListView().getItems().indexOf(getItem());
                if(nIndex < getListView().getItems().size() - 1) {
                    getListView().getItems().remove(preModel);
                    getListView().getItems().add(nIndex + 1, preModel);

                    getListView().getSelectionModel().select(preModel);

                    changeIndex();
                }
            }
        });

    }

    private void setListCell() {
        listCell = this;
    }

    /**
     * セル更新
     *
     * @param item
     * @param empty
     */
    @Override
    public void updateItem(PreModel item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            super.setText(item.getName());

            ImageView icon;

            if (getItem().isDownloadFlg()) {
                icon = new ImageView(new Image("it/trick/admin/resource/images/public_page.png"));
            } else {
                icon = new ImageView(new Image("it/trick/admin/resource/images/no_public.png"));
            }
            icon.setFitHeight(18.0);
            icon.setPreserveRatio(true);
            setGraphic(icon);

            // コンテキストメニュー
            setContextMenu(contextMenu);
            // マウスイベント
            this.setOnMouseClicked(new EventHandler<MouseEvent>() {
                @Override
                public void handle(MouseEvent t) {
                    // コンテキストメニュー表示イベント
                    if (t.isControlDown()) {
                        getContextMenu().show(listCell, t.getScreenX(), t.getScreenY());

                        // 編集イベント（ダブルクリック）
                    } else if (t.getClickCount() == 2) {
                        AddPreViewController addController = new AddPreViewController(getItem());
                        App.getInstance().showPopStage(addController, "ソース変更", 600, 600, false);
                    }
                }
            });

            // ドラッグイベントの設定
            setDragEvent();

        }
    }


    /**
     * コンテンツ削除
     * @return
     */
    private Pane getDeleteStageController() {
        ContentsBaseModel baseModel = getItem();
        DeleteContentsViewController controller = new DeleteContentsViewController(baseModel.getName());

        controller.deleteButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {

                // POST処理
                ChannelTopController.getInstance().deletePreTask.setup(getItem().getKeyValueString());
                ChannelTopController.getInstance().deletePreTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
                    @Override
                    public void handle(WorkerStateEvent t) {
                        getListView().getItems().remove(getItem());
                    }
                });
                ChannelTopController.getInstance().deletePreTask.restart();

                App.getInstance().closePopStage();
            }
        });

        return controller;
    }

    /**
     * 順序の更新
     */
    private void changeIndex() {

        List<ContentsBaseModel> modelList = new ArrayList();

        for(PreModel model: getListView().getItems()) {
            modelList.add((ContentsBaseModel)model);
        }

        ChannelTopController.getInstance().changeIndexTask.setup(modelList);
        ChannelTopController.getInstance().changeIndexTask.restart();
    }

    private void setDragEvent() {
        // ---------------------------------------------------------------------
        // ドラッグ 開始
        // ---------------------------------------------------------------------
        this.setOnDragDetected(
                new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {

                // カテゴリパスの設定
                PreModel preModel = getItem();

                String clipdString = "@@" + preModel.getKeyValueString() + "@@";

                // ドラッグボードの設定
                Dragboard db = getListView().startDragAndDrop(TransferMode.COPY);
                ClipboardContent clipd = new ClipboardContent();
                clipd.putString(clipdString);
                db.setContent(clipd);
            }
        });
    }
}
